import { LogoutOutlined, SettingOutlined, UserOutlined, BellOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin, Badge, Tooltip, List, Comment, message } from 'antd';
import NoticeIcon from '../NoticeIcon';
import React from 'react';
import { history, connect } from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { DeleteNotice, getNotice, putNotice } from './service';
class AvatarDropdown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      notice: [],
      num: 0,
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'login/fetchCurrent',
      });
    }
    this.handleMessage();
  }
  handleMessage = () => {
    const { roleName } = JSON.parse(sessionStorage.getItem('userInfo'));
    getNotice({ to: roleName })
      .then((res) => {
        const { code } = res;
        code === 0
          ? this.setState({
              notice: res.data,
              num: res.data.length,
            })
          : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  onMenuClick = (event) => {
    const { key } = event;

    if (key === 'logout') {
      const { dispatch } = this.props;

      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
        sessionStorage.clear()
      }

      return;
    }
    if (key === 'changePwd') {
      const { dispatch } = this.props;
      if (dispatch) {
        dispatch({
          type: 'global/changePwdShow',
          payload: true,
        });
      }

      return;
    }

    history.push(`/account/${key}`);
  };
  handleNoticeClear = (title, key) => {
    message.success(`${'清空了'} ${title}`);
    this.setState({
      notice: [],
      num: 0,
    });
  };

  render() {
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
    const {
      currentUser = {
        roleName: '',
        name: '',
      },
      menu,
    } = this.props;
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {menu && (
          <Menu.Item key="center">
            <UserOutlined />
            个人中心
          </Menu.Item>
        )}
        {menu && (
          <Menu.Item key="settings">
            <SettingOutlined />
            个人设置
          </Menu.Item>
        )}
        {menu && <Menu.Divider />}
        <Menu.Item key="changePwd">
          <SettingOutlined />
          修改密码
        </Menu.Item>
        <Menu.Item key="logout">
          <LogoutOutlined />
          退出登录
        </Menu.Item>
      </Menu>
    );
    const menuNotice = (
      <NoticeIcon
        className={styles.action}
        count={currentUser && currentUser.unreadCount}
        onItemClick={(item, index) => {
          // this.changeReadState(item);
          DeleteNotice(item.id)
            .then((res) => {
              const { code } = res;
              code === 0 ? this.handleMessage() : message.info(res.message);
            })
            .catch((err) => {
              console.log(err);
            });
        }}
        loading={this.props.fetchingNotices}
        onClear={this.handleNoticeClear}
        onPopupVisibleChange={this.props.onNoticeVisibleChange}
      >
        <NoticeIcon.Tab
          tabKey="message"
          count={this.state.num}
          list={this.state.notice}
          title="通知"
          emptyText="你已查看所有通知"
          showViewMore
        />
      </NoticeIcon>
    );
    return currentUser && currentUser.name ? (
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <Badge count={this.state.notice.length}>{menuNotice}</Badge>

        <HeaderDropdown overlay={menuHeaderDropdown}>
          <span className={`${styles.action} ${styles.account}`}>
            角色：<span className={`${styles.name} anticon`}>{currentUser.roleName}</span>，
            用户名：
            <span className={`${styles.name} anticon`}>{currentUser.name}</span>
          </span>
        </HeaderDropdown>
      </div>
    ) : (
      <span className={`${styles.action} ${styles.account}`}>
        <Spin
          size="small"
          style={{
            marginLeft: 8,
            marginRight: 8,
          }}
        />
      </span>
    );
  }
}

export default connect(({ login, global }) => ({
  currentUser: login.currentUser,
}))(AvatarDropdown);
